<template>
  <div class="login-container">
    <!-- Logo在左上角 -->
    <div class="logo-section">
      <img src="/MatCreate AI-黑色字体.png" alt="MatCreate AI" class="logo" />
    </div>

    <div class="login-box">
      <!-- 欢迎标题 -->
      <div class="welcome-section">
        <h1 class="welcome-title">欢迎回来</h1>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label class="form-label">用户名或邮箱</label>
          <input
            type="text"
            v-model="loginForm.username"
            placeholder="请输入用户名或邮箱"
            required
            class="form-input"
          >
        </div>
        <div class="form-group">
          <label class="form-label">密码</label>
          <input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
            required
            class="form-input"
          >
        </div>

        <div v-if="loginError" class="error-message">
          {{ loginError }}
        </div>

        <button type="submit" class="continue-btn" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '继续' }}
        </button>
      </form>

      <!-- 注册链接 -->
      <div class="register-section">
        <span class="register-text">还没有账户？</span>
        <button type="button" @click="showRegister = true" class="register-link">
          注册
        </button>
      </div>
    </div>

    <!-- 注册弹窗 -->
    <div v-if="showRegister" class="register-modal" @click="closeRegisterModal">
      <div class="register-box" @click.stop>
        <div class="modal-header">
          <h2>创建您的账户</h2>
          <button class="close-btn" @click="showRegister = false">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </button>
        </div>

        <div class="modal-content">
          <form @submit.prevent="handleRegister" class="register-form">
            <div class="form-group">
              <label class="form-label">用户名</label>
              <input
                type="text"
                v-model="registerForm.username"
                placeholder="请输入用户名"
                required
                class="form-input"
                minlength="3"
                maxlength="20"
              >
            </div>

            <div class="form-group">
              <label class="form-label">邮箱</label>
              <input
                type="email"
                v-model="registerForm.email"
                placeholder="请输入邮箱地址"
                required
                class="form-input"
              >
            </div>

            <div class="form-group">
              <label class="form-label">密码</label>
              <input
                type="password"
                v-model="registerForm.password"
                placeholder="请输入密码"
                required
                class="form-input"
                minlength="6"
              >
            </div>

            <div class="form-group">
              <label class="form-label">确认密码</label>
              <input
                type="password"
                v-model="registerForm.confirmPassword"
                placeholder="请再次输入密码"
                required
                class="form-input"
              >
            </div>

            <div v-if="registerError" class="error-message">
              {{ registerError }}
            </div>

            <button type="submit" class="continue-btn" :disabled="isLoading">
              {{ isLoading ? '创建中...' : '创建账户' }}
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { userStore } from '../stores/user'
import { authAPI } from '../services/api'

const router = useRouter()
const route = useRoute()
const isLoading = ref(false)
const loginError = ref('')
const registerError = ref('')
const showRegister = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 关闭注册弹窗
const closeRegisterModal = () => {
  showRegister.value = false
}

const handleLogin = async () => {
  try {
    isLoading.value = true
    loginError.value = ''
    
    const response = await authAPI.login(loginForm.username, loginForm.password)
    
    if (response.code === 200) {
      // 登录成功，存储token
      const token = response.data?.tokenValue
      const userId = response.data?.loginId
      if (token) {
        localStorage.setItem('token', token)
        localStorage.setItem('username', loginForm.username)
        localStorage.setItem('loginId', userId)

        // 同步全局用户状态
        userStore.username = loginForm.username
        userStore.isLogin = true

        // 跳转到首页，如果有来源页面则返回来源页面
        const redirect = route.query.redirect || '/'
        router.push(redirect)
      } else {
        loginError.value = '登录成功但未能获取到token'
      }
    } else {
      loginError.value = response.msg || '登录失败'
    }
  } catch (error) {
    console.error('登录失败:', error)
    loginError.value = error.msg || error.message || '登录失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

const handleRegister = async () => {
  try {
    // 表单验证
    if (!registerForm.username.trim()) {
      registerError.value = '请输入用户名'
      return
    }

    if (registerForm.username.length < 3 || registerForm.username.length > 20) {
      registerError.value = '用户名长度应在3-20个字符之间'
      return
    }

    if (!registerForm.email.trim()) {
      registerError.value = '请输入邮箱地址'
      return
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
      registerError.value = '请输入有效的邮箱地址'
      return
    }

    if (!registerForm.password) {
      registerError.value = '请输入密码'
      return
    }

    if (registerForm.password.length < 6) {
      registerError.value = '密码长度至少6个字符'
      return
    }

    if (registerForm.password !== registerForm.confirmPassword) {
      registerError.value = '两次输入的密码不一致'
      return
    }

    isLoading.value = true
    registerError.value = ''

    const response = await authAPI.register(
      registerForm.username,
      registerForm.password
    )

    if (response.code === 200) {
      // 注册成功，关闭弹窗并填充登录表单
      showRegister.value = false
      loginForm.username = registerForm.username
      // 清空注册表单
      Object.assign(registerForm, {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      })
      // 显示成功提示
      alert('🎉 注册成功！请使用您的账户登录。')
    } else {
      registerError.value = response.msg || '注册失败，请稍后重试'
    }
  } catch (error) {
    console.error('注册失败:', error)
    registerError.value = error.msg || error.message || '注册失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafbfc; // 更浅的背景颜色
  z-index: 1000;

  // Logo样式
  .logo-section {
    position: absolute;
    top: 2rem;
    left: 2rem;
    z-index: 1001;

    .logo {
      height: 40px;
      width: auto;
      object-fit: contain;
      transition: all 0.2s ease;

      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .login-box {
    width: 100%;
    max-width: 400px;
    background: white;
    border-radius: 12px;
    padding: 2.5rem;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(0, 0, 0, 0.1);

    .welcome-section {
      text-align: center;
      margin-bottom: 2rem;

      .welcome-title {
        font-size: 2rem;
        font-weight: 600;
        color: #2d3748;
        margin: 0;
        letter-spacing: -0.025em;
      }
    }

    .login-form {
      .form-group {
        margin-bottom: 1.5rem;

        .form-label {
          display: block;
          margin-bottom: 0.5rem;
          color: #374151;
          font-weight: 500;
          font-size: 0.875rem;
        }

        .form-input {
          width: 100%;
          padding: 0.875rem 1rem;
          border: 1px solid #d1d5db;
          border-radius: 8px;
          font-size: 1rem;
          transition: all 0.2s ease;
          background: #fff;

          &:focus {
            outline: none;
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
          }

          &::placeholder {
            color: #9ca3af;
          }
        }
      }

      .error-message {
        color: #ef4444;
        margin-bottom: 1rem;
        font-size: 0.875rem;
        padding: 0.75rem;
        background: #fef2f2;
        border: 1px solid #fecaca;
        border-radius: 8px;
      }

      .continue-btn {
        width: 100%;
        padding: 0.875rem;
        background: #000;
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 1rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover:not(:disabled) {
          background: #1f2937;
        }

        &:disabled {
          background: #9ca3af;
          cursor: not-allowed;
        }
      }
    }

    .register-section {
      text-align: center;
      margin-top: 1.5rem;
      font-size: 0.875rem;
      color: #6b7280;

      .register-text {
        margin-right: 0.25rem;
      }

      .register-link {
        background: none;
        border: none;
        color: #10b981;
        font-weight: 500;
        cursor: pointer;
        text-decoration: none;
        font-size: 0.875rem;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }

  // 注册弹窗样式
  .register-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1001;
    padding: 1rem;

    .register-box {
      width: 100%;
      max-width: 500px;
      background: white;
      border-radius: 16px;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
      max-height: 90vh;
      overflow-y: auto;
      animation: modalSlideIn 0.3s ease-out;

      .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 2rem 2.5rem 1rem;
        border-bottom: 1px solid #f1f5f9;

        h2 {
          margin: 0;
          font-size: 1.75rem;
          font-weight: 700;
          color: #1e293b;
          letter-spacing: -0.025em;
        }

        .close-btn {
          background: none;
          border: none;
          color: #64748b;
          cursor: pointer;
          padding: 0.5rem;
          border-radius: 8px;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;

          &:hover {
            background: #f1f5f9;
            color: #334155;
          }
        }
      }

      .modal-content {
        padding: 1rem 2.5rem 2.5rem;

        .register-form {
          .form-group {
            margin-bottom: 1.5rem;

            .form-label {
              display: block;
              margin-bottom: 0.5rem;
              color: #374151;
              font-weight: 600;
              font-size: 0.875rem;
            }

            .form-input {
              width: 100%;
              padding: 0.875rem 1rem;
              border: 2px solid #e2e8f0;
              border-radius: 10px;
              font-size: 0.95rem;
              transition: all 0.2s ease;
              background: #fff;

              &:focus {
                outline: none;
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
              }

              &::placeholder {
                color: #94a3b8;
              }
            }
          }

          .error-message {
            color: #ef4444;
            margin-bottom: 1rem;
            font-size: 0.875rem;
            padding: 0.75rem;
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-radius: 8px;
          }

          .continue-btn {
            width: 100%;
            padding: 1rem;
            background: #000;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;

            &:hover:not(:disabled) {
              background: #1f2937;
              transform: translateY(-1px);
            }

            &:disabled {
              background: #9ca3af;
              cursor: not-allowed;
              transform: none;
            }
          }
        }
      }
    }
  }

  @keyframes modalSlideIn {
    from {
      opacity: 0;
      transform: translateY(-20px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 1rem;

    .logo-section {
      top: 1rem;
      left: 1rem;

      .logo {
        height: 32px;
      }
    }

    .login-box {
      max-width: none;
      padding: 2rem 1.5rem;
      margin: 0;

      .welcome-section .welcome-title {
        font-size: 1.75rem;
      }

      .login-form {
        .form-group .form-input {
          padding: 0.75rem;
          font-size: 16px; // 防止iOS缩放
        }

        .continue-btn {
          padding: 0.75rem;
          font-size: 1rem;
        }
      }
    }

    .register-modal .register-box {
      margin: 1rem;
      max-width: none;

      .modal-header {
        padding: 1.5rem 1.5rem 1rem;

        h2 {
          font-size: 1.5rem;
        }
      }

      .modal-content {
        padding: 1rem 1.5rem 2rem;
      }
    }
  }
}

@media (max-width: 480px) {
  .login-container {
    .logo-section {
      top: 0.75rem;
      left: 0.75rem;

      .logo {
        height: 28px;
      }
    }

    .login-box {
      padding: 1.5rem 1rem;

      .welcome-section .welcome-title {
        font-size: 1.5rem;
      }
    }
  }
}
</style> 